package com.windchime.blog.controller;

import com.windchime.blog.entity.User;
import com.windchime.blog.entity.vo.UserFrontVo;
import com.windchime.blog.result.R;
import com.windchime.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class FrontUserController {

    @Autowired
    private UserService userService;

    /**
     * 去到登录页
     * @return login
     */
    @GetMapping("/login")
    public String login() {
        return "login";
    }

    /**
     * 登录方法
     * @param userFrontVo 登录对象
     * @return user
     */
    @PostMapping("/user/login")
    @ResponseBody
    public R userLogin(UserFrontVo userFrontVo) {
        User user = userService.userLogin(userFrontVo);
        if (!StringUtils.isEmpty(user)) {
            user.setPassword("");
            return R.ok().msg("登录成功").data("user", user);
        } else {
            return R.error().msg("登录失败");
        }
    }

    /**
     * 注销方法
     * @return true
     */
    @PostMapping("/user/logout")
    @ResponseBody
    public R userLogout() {
        return R.ok().msg("注销成功");
    }

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    /**
     * 注册方法
     * @param userFrontVo 注册对象
     * @return user
     */
    @PostMapping("/user/register")
    @ResponseBody
    public R userRegister(UserFrontVo userFrontVo) {
        boolean b = userService.userRegister(userFrontVo);
        if (b) {
            return R.ok().msg("注册成功");
        } else {
            return R.error().msg("已有该用户名,注册失败");
        }
    }

}
